package cn.xiuxius.embedded.livetemplate;

import com.intellij.codeInsight.template.TemplateActionContext;
import com.intellij.codeInsight.template.TemplateContextType;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import org.jetbrains.annotations.NotNull;

public class FunctionScopeContextType extends TemplateContextType {

    protected FunctionScopeContextType() {
        super("STC_C_CPP_FUNCTION_SCOPE");
    }

    @Override
    public boolean isInContext(@NotNull TemplateActionContext context) {
        PsiFile file = context.getFile();
        String fileName = file.getName().toLowerCase();

        if (!fileName.endsWith(".c") && !fileName.endsWith(".cpp")) {
            return false;
        }

        int offset = context.getStartOffset();
        PsiElement element = file.findElementAt(offset);
        if (element == null) return false;

        return isInFunctionBody(element);
    }

    private boolean isInFunctionBody(PsiElement element) {
        while (element != null) {
            if (isCurlyBraceBlock(element)) {
                if (belongsToFunction(element)) {
                    return true;
                }
            }
            element = element.getParent();
        }
        return false;
    }

    private boolean isCurlyBraceBlock(PsiElement element) {
        String text = element.getText();
        if (text == null) return false;
        text = text.trim();
        return text.startsWith("{") && text.endsWith("}");
    }

    private boolean belongsToFunction(PsiElement blockElement) {
        PsiElement prevSibling = blockElement.getPrevSibling();
        while (prevSibling != null) {
            String text = prevSibling.getText();
            if (text != null && text.contains(")")) {
                return true;
            }
            prevSibling = prevSibling.getPrevSibling();
        }
        return false;
    }
}
